# main.py
import pandas as pd
import yaml
import os
import importlib.util
from frame.ConstructionDataProcessor import ConstructionDataProcessor


def load_class(module_path, class_name):
    spec = importlib.util.spec_from_file_location(
        class_name,
        os.path.join(os.getcwd(), f"{module_path}.py")
    )
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return getattr(module, class_name)


def process_project_type(project_type, filtered_df):
    name = project_type["type_name"]
    print(f"\n🔄 正在处理项目类型: {name}")

    # Step 1: 筛选当前类型的数据
    current_df = filtered_df[filtered_df['类型'] == name]
    if current_df.empty:
        print(f"[跳过] 当前类型无数据: {name}")
        return

    # Step 2: 加载 YAML 更新器类
    updater_module_path, updater_class_name = project_type["updater_class"].split(":")
    YAMLUpdaterClass = load_class(updater_module_path, updater_class_name)
    updater = YAMLUpdaterClass(filepath=project_type["template_file"])

    print(f"✅ 使用模板: {project_type['template_file']}")
    print(f"✅ 使用更新器: {project_type['updater_class']}")

    # Step 3: 执行 YAML 更新器
    all_processed_data = updater.run(current_df)

    # Step 4: 加载规则配置类
    rule_module_path, rule_class_name = project_type["rule_config_class"].split(":")
    RuleConfigClass = load_class(rule_module_path, rule_class_name)
    rule_processor = RuleProcessor(rule_config=RuleConfigClass())

    print(f"✅ 使用规则配置: {project_type['rule_config_class']}")

    # Step 5: 执行规则引擎
    for data in all_processed_data.values():
        rule_processor.write_project_to_excel(data, output_dir="outputs")

    print(f"✅ 类型 [{name}] 处理完成")


if __name__ == "__main__":
    from model import RuleProcessor

    # Step 1: 获取原始数据
    processor = ConstructionDataProcessor()
    final_df = processor.process()

    # Step 2: 清洗和过滤数据
    filtered_df = final_df.dropna(how='any')

    # Step 3: 加载项目类型定义
    with open("config/project_types.yaml", "r", encoding="utf-8") as f:
        config = yaml.safe_load(f)
        project_types = config["project_types"]

    print("\n📋 可用项目类型：")
    for idx, pt in enumerate(project_types, 1):
        print(f"{idx}. {pt['type_name']}")

    print("\n📌 输入要处理的项目类型编号（多个用空格分隔，按回车处理全部）:")
    choice = '1'

    selected_types = []
    if not choice:
        selected_types = project_types
    else:
        try:
            indices = list(map(int, choice.split()))
            selected_types = [project_types[i - 1] for i in indices if 0 < i <= len(project_types)]
        except Exception as e:
            print("[错误] 输入格式不正确，默认处理全部类型。")
            selected_types = project_types

    print("\n🚀 即将处理以下项目类型：")
    for t in selected_types:
        print(f" - {t['type_name']}")

    # Step 4: 对选中项目类型分别处理
    for project_type in selected_types:
        process_project_type(project_type, filtered_df)

    print("\n🎉 所有选定项目类型处理完成！")